package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.github.gzuliyujiang.wheelpicker.AddressPicker;
import com.github.gzuliyujiang.wheelpicker.BirthdayPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity;
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity;
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.moyun.modelclass.R;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.dialog.CommonBottomDialog;
import com.moyun.modelclass.dialog.GenderDialog;
import com.moyun.modelclass.event.LoginStateEvent;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppAuthLogoutApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.api.UserInfoApi;
import com.moyun.modelclass.http.api.UserSaveApi;
import com.moyun.modelclass.http.bean.CommonDialogBean;
import com.moyun.modelclass.http.bean.LoginInfoResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.listener.OnContentListener;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.GlideEngine;
import com.moyun.modelclass.utils.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 作者：Meteor
 * 日期：2022/2/81:39 上午
 * tip：个人资料
 */
public class PersonalInformationActivity extends BaseActivity implements OnAddressPickedListener, OnDatePickedListener {
    private RelativeLayout rlPersonalInformationTop;
    private ImageView personalInformationBack;
    private RelativeLayout personalInformationUserNameAll;
    private TextView personalInformationUserName;
    private RelativeLayout personalInformationHeadPortraitAll;
    private ImageView personalInformationHeadPortraitImage;
    private RelativeLayout personalInformationBackgroundAll;
    private ImageView personalInformationBackgroundImage;
    private RelativeLayout personalInformationGenderAll;
    private TextView personalInformationGender;
    private RelativeLayout personalInformationAgeAll;
    private TextView personalInformationAge;
    private RelativeLayout personalInformationJobAll;
    private TextView personalInformationJob;
    private RelativeLayout personalInformationHobbyAll;
    private TextView personalInformationHobby;
    private RelativeLayout personalInformationCityAll;
    private TextView personalInformationCity;
    private RelativeLayout personalInformationIntroduceAll;
    private TextView personalInformationIntroduce;
    private TextView personalInformationLogOut;

    //1:昵称；2：职业；3：专业领域/爱好；4：个人介绍
    public static final String KEY_PERSONAL_INFORMATION_ID = "KEY_PERSONAL_INFORMATION_ID";
    public static final int KEY_USER_NAME_ID = 1101;
    public static final int KEY_JOB_ID = 1102;
    public static final int KEY_HOBBY_ID = 1103;
    public static final int KEY_INFORMATION_ID = 1104;

    private String mAreaCode = "110101";

    private String mProvince = "北京市";//省
    private String mCity = "北京市";//市
    private String mArea = "东城区";//区

    private String headImageBean = "";//头像图片
    private String backgroundImageBean = "";//背景图片
    private int mGender = 1;//1：男，2：女
    private String mBirthday = "1999-04-18";//生日
    private List<String> mSpecialityList = new ArrayList<>();//已编辑专业领域/爱好

    public static void start(Context context) {
        Intent starter = new Intent(context, PersonalInformationActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_personal_information;
    }

    @Override
    protected void assignViews() {
        rlPersonalInformationTop = (RelativeLayout) findViewById(R.id.rl_personal_information_top);
        personalInformationBack = (ImageView) findViewById(R.id.personal_information_back);
        personalInformationUserNameAll = (RelativeLayout) findViewById(R.id.personal_information_user_name_all);
        personalInformationUserName = (TextView) findViewById(R.id.personal_information_user_name);
        personalInformationHeadPortraitAll = (RelativeLayout) findViewById(R.id.personal_information_head_portrait_all);
        personalInformationHeadPortraitImage = (ImageView) findViewById(R.id.personal_information_head_portrait_image);
        personalInformationBackgroundAll = (RelativeLayout) findViewById(R.id.personal_information_background_all);
        personalInformationBackgroundImage = (ImageView) findViewById(R.id.personal_information_background_image);
        personalInformationGenderAll = (RelativeLayout) findViewById(R.id.personal_information_gender_all);
        personalInformationGender = (TextView) findViewById(R.id.personal_information_gender);
        personalInformationAgeAll = (RelativeLayout) findViewById(R.id.personal_information_age_all);
        personalInformationAge = (TextView) findViewById(R.id.personal_information_age);
        personalInformationJobAll = (RelativeLayout) findViewById(R.id.personal_information_job_all);
        personalInformationJob = (TextView) findViewById(R.id.personal_information_job);
        personalInformationHobbyAll = (RelativeLayout) findViewById(R.id.personal_information_hobby_all);
        personalInformationHobby = (TextView) findViewById(R.id.personal_information_hobby);
        personalInformationCityAll = (RelativeLayout) findViewById(R.id.personal_information_city_all);
        personalInformationCity = (TextView) findViewById(R.id.personal_information_city);
        personalInformationIntroduceAll = (RelativeLayout) findViewById(R.id.personal_information_introduce_all);
        personalInformationIntroduce = (TextView) findViewById(R.id.personal_information_introduce);
        personalInformationLogOut = (TextView) findViewById(R.id.personal_information_log_out);


        StatusBarUtil.setPaddingSmart(this, rlPersonalInformationTop);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(personalInformationBack, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //用户名
        ClickUtils.applySingleDebouncing(personalInformationUserNameAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditPersonalInformationActivity.start(PersonalInformationActivity.this, 1, personalInformationUserName.getText().toString(), KEY_USER_NAME_ID);
            }
        });

        //头像
        ClickUtils.applySingleDebouncing(personalInformationHeadPortraitAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<CommonDialogBean> dataList = new ArrayList<>();
                dataList.add(new CommonDialogBean("1", "拍照"));
                dataList.add(new CommonDialogBean("2", "从手机相册选择"));
                dataList.add(new CommonDialogBean("-1", "取消"));
                CommonBottomDialog.getInstance(PersonalInformationActivity.this, "", dataList, new OnContentListener() {
                    @Override
                    public void content(int id, CommonDialogBean content) {
                        if (content.getMessage().equals("拍照")) {
                            XXPermissions.with(mActivity).permission(Permission.CAMERA)
                                    .request(new OnPermissionCallback() {
                                        @Override
                                        public void onGranted(List<String> permissions, boolean all) {
                                            PictureSelector.create(mActivity)
                                                    .openCamera(SelectMimeType.ofImage())
                                                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                                                        @Override
                                                        public void onResult(ArrayList<LocalMedia> result) {
                                                            for (LocalMedia media : result) {
                                                                Luban.with(mActivity)
                                                                        .load(media.getRealPath())
                                                                        .ignoreBy(50)
                                                                        .setTargetDir(CreateFileUtils.getSandboxPath(mActivity))
                                                                        .setCompressListener(new OnCompressListener() {
                                                                                                 @Override
                                                                                                 public void onStart() {

                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onSuccess(int index, File compressFile) {
                                                                                                     Glide.with(mContext)
                                                                                                             .asBitmap()
                                                                                                             .centerCrop()
                                                                                                             .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                                             .placeholder(R.drawable.icon_head_portrait)
                                                                                                             .error(R.drawable.icon_head_portrait)
                                                                                                             .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                                                                                             .into(new BitmapImageViewTarget(personalInformationHeadPortraitImage) {
                                                                                                                 @Override
                                                                                                                 protected void setResource(Bitmap resource) {
                                                                                                                     super.setResource(resource);
                                                                                                                     personalInformationHeadPortraitImage.setImageBitmap(ImageUtils.toRound(resource));
                                                                                                                 }
                                                                                                             });
                                                                                                     initUpdateImageApi(true, true, compressFile);
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onError(int index, Throwable e) {
                                                                                                 }
                                                                                             }
                                                                        ).launch();
                                                            }
                                                        }

                                                        @Override
                                                        public void onCancel() {

                                                        }
                                                    });
                                        }

                                        @Override
                                        public void onDenied(List<String> permissions, boolean never) {
                                            ToastUtils.showShort("获取相机权限失败");
                                        }
                                    });
                        } else if (content.getMessage().equals("从手机相册选择")) {
                            XXPermissions.with(PersonalInformationActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                                    .request(new OnPermissionCallback() {
                                        @Override
                                        public void onGranted(List<String> permissions, boolean all) {
                                            PictureSelector.create(PersonalInformationActivity.this)
                                                    .openGallery(SelectMimeType.ofImage())
                                                    .setImageEngine(GlideEngine.createGlideEngine())
                                                    .setMaxSelectNum(1)
                                                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                                                        @Override
                                                        public void onResult(ArrayList<LocalMedia> result) {
                                                            for (LocalMedia media : result) {
                                                                Luban.with(PersonalInformationActivity.this)
                                                                        .load(media.getRealPath())
                                                                        .ignoreBy(50)
                                                                        .setTargetDir(CreateFileUtils.getSandboxPath(PersonalInformationActivity.this))
                                                                        .setCompressListener(new OnCompressListener() {
                                                                                                 @Override
                                                                                                 public void onStart() {
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onSuccess(int index, File compressFile) {
                                                                                                     Glide.with(mContext)
                                                                                                             .asBitmap()
                                                                                                             .centerCrop()
                                                                                                             .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                                             .placeholder(R.drawable.icon_head_portrait)
                                                                                                             .error(R.drawable.icon_head_portrait)
                                                                                                             .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                                                                                             .into(new BitmapImageViewTarget(personalInformationHeadPortraitImage) {
                                                                                                                 @Override
                                                                                                                 protected void setResource(Bitmap resource) {
                                                                                                                     super.setResource(resource);
                                                                                                                     personalInformationHeadPortraitImage.setImageBitmap(ImageUtils.toRound(resource));
                                                                                                                 }
                                                                                                             });
                                                                                                     initUpdateImageApi(true, true, compressFile);
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onError(int index, Throwable e) {
                                                                                                 }
                                                                                             }
                                                                        ).launch();
                                                            }
                                                        }

                                                        @Override
                                                        public void onCancel() {

                                                        }
                                                    });
                                        }

                                        @Override
                                        public void onDenied(List<String> permissions, boolean never) {
                                            ToastUtils.showShort("获取存储权限失败");
                                        }
                                    });
                        }
                    }
                }).builder().show();
            }
        });

        //背景图
        ClickUtils.applySingleDebouncing(personalInformationBackgroundAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<CommonDialogBean> dataList = new ArrayList<>();
                dataList.add(new CommonDialogBean("1", "拍照"));
                dataList.add(new CommonDialogBean("2", "从手机相册选择"));
                dataList.add(new CommonDialogBean("-1", "取消"));
                CommonBottomDialog.getInstance(PersonalInformationActivity.this, "", dataList, new OnContentListener() {
                    @Override
                    public void content(int id, CommonDialogBean content) {
                        if (content.getMessage().equals("拍照")) {
                            XXPermissions.with(PersonalInformationActivity.this).permission(Permission.CAMERA)
                                    .request(new OnPermissionCallback() {
                                        @Override
                                        public void onGranted(List<String> permissions, boolean all) {
                                            PictureSelector.create(PersonalInformationActivity.this)
                                                    .openCamera(SelectMimeType.ofImage())
                                                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                                                        @Override
                                                        public void onResult(ArrayList<LocalMedia> result) {
                                                            for (LocalMedia media : result) {
                                                                Luban.with(PersonalInformationActivity.this)
                                                                        .load(media.getRealPath())
                                                                        .ignoreBy(50)
                                                                        .setTargetDir(CreateFileUtils.getSandboxPath(mActivity))
                                                                        .setCompressListener(new OnCompressListener() {
                                                                                                 @Override
                                                                                                 public void onStart() {
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onSuccess(int index, File compressFile) {
                                                                                                     Glide.with(PersonalInformationActivity.this)
                                                                                                             .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                                             .centerInside()
                                                                                                             .diskCacheStrategy(DiskCacheStrategy.ALL)
                                                                                                             .into(personalInformationBackgroundImage);
                                                                                                     initUpdateImageApi(true, false, compressFile);
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onError(int index, Throwable e) {
                                                                                                 }
                                                                                             }
                                                                        ).launch();
                                                            }
                                                        }

                                                        @Override
                                                        public void onCancel() {
                                                        }
                                                    });
                                        }

                                        @Override
                                        public void onDenied(List<String> permissions, boolean never) {
                                            ToastUtils.showShort("获取相机权限失败");
                                        }
                                    });
                        } else if (content.getMessage().equals("从手机相册选择")) {
                            XXPermissions.with(PersonalInformationActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                                    .request(new OnPermissionCallback() {
                                        @Override
                                        public void onGranted(List<String> permissions, boolean all) {
                                            PictureSelector.create(PersonalInformationActivity.this)
                                                    .openGallery(SelectMimeType.ofImage())
                                                    .setImageEngine(GlideEngine.createGlideEngine())
                                                    .setMaxSelectNum(1)
                                                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                                                        @Override
                                                        public void onResult(ArrayList<LocalMedia> result) {
                                                            for (LocalMedia media : result) {
                                                                Luban.with(PersonalInformationActivity.this)
                                                                        .load(media.getRealPath())
                                                                        .ignoreBy(50)
                                                                        .setTargetDir(CreateFileUtils.getSandboxPath(PersonalInformationActivity.this))
                                                                        .setCompressListener(new OnCompressListener() {
                                                                                                 @Override
                                                                                                 public void onStart() {
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onSuccess(int index, File compressFile) {
                                                                                                     Glide.with(PersonalInformationActivity.this)
                                                                                                             .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                                             .centerInside()
                                                                                                             .diskCacheStrategy(DiskCacheStrategy.ALL)
                                                                                                             .into(personalInformationBackgroundImage);
                                                                                                     initUpdateImageApi(true, false, compressFile);
                                                                                                 }

                                                                                                 @Override
                                                                                                 public void onError(int index, Throwable e) {
                                                                                                 }
                                                                                             }
                                                                        ).launch();
                                                            }
                                                        }

                                                        @Override
                                                        public void onCancel() {
                                                        }
                                                    });
                                        }

                                        @Override
                                        public void onDenied(List<String> permissions, boolean never) {
                                            ToastUtils.showShort("获取存储权限失败");
                                        }
                                    });
                        }
                    }
                }).builder().show();
            }
        });

        //性别
        ClickUtils.applySingleDebouncing(personalInformationGenderAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GenderDialog.getInstance(mActivity, mGender, new GenderDialog.OnGenderListener() {
                    @Override
                    public void content(int gender) {
                        mGender = gender;
                        personalInformationGender.setText(gender == 1 ? "男" : "女");
                        saveUserInfo();
                    }
                }).builder().show();
            }
        });

        //生日
        ClickUtils.applySingleDebouncing(personalInformationAgeAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBirthday();
            }
        });

        //工作
        ClickUtils.applySingleDebouncing(personalInformationJobAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditPersonalInformationActivity.start(PersonalInformationActivity.this, 2, personalInformationJob.getText().toString(), KEY_JOB_ID);
            }
        });

        //爱好
        ClickUtils.applySingleDebouncing(personalInformationHobbyAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditSpecialityActivity.start(PersonalInformationActivity.this, mSpecialityList, KEY_HOBBY_ID);
            }
        });

        //所在城市
        ClickUtils.applySingleDebouncing(personalInformationCityAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onProvinceCityCounty();
            }
        });

        //自我介绍
        ClickUtils.applySingleDebouncing(personalInformationIntroduceAll, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditPersonalInformationActivity.start(PersonalInformationActivity.this, 4, personalInformationIntroduce.getText().toString(), KEY_INFORMATION_ID);
            }
        });

        //退出登录
        ClickUtils.applySingleDebouncing(personalInformationLogOut, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                authLogout();
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {

    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initUserInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == KEY_USER_NAME_ID) {
                //1:昵称
                String name = data.getStringExtra(KEY_PERSONAL_INFORMATION_ID);
                personalInformationUserName.setText(name);
            } else if (requestCode == KEY_JOB_ID) {
                //职业
                String job = data.getStringExtra(KEY_PERSONAL_INFORMATION_ID);
                personalInformationJob.setText(job);
            } else if (requestCode == KEY_HOBBY_ID) {
                //专业领域/爱好
                mSpecialityList = data.getStringArrayListExtra(KEY_PERSONAL_INFORMATION_ID);
                if (mSpecialityList != null && mSpecialityList.size() > 0) {
                    StringBuilder speciality = new StringBuilder();
                    for (int i = 0; i < mSpecialityList.size(); i++) {
                        //证明是最后一个
                        if (i == mSpecialityList.size() - 1) {
                            speciality.append(mSpecialityList.get(i));
                        } else {
                            speciality.append(mSpecialityList.get(i)).append("，");
                        }
                    }
                    personalInformationHobby.setText(speciality);
                } else {
                    personalInformationHobby.setText("");
                }
            } else if (requestCode == KEY_INFORMATION_ID) {
                //个人介绍
                String information = data.getStringExtra(KEY_PERSONAL_INFORMATION_ID);
                personalInformationIntroduce.setText(information);
            }
            saveUserInfo();
        }
    }

    @SuppressLint("SetTextI18n")
    private void initUserInfo() {
        EasyHttp.post(this)
                .api(new UserInfoApi().setUserId(CommonConfiguration.getUseId(kv)))
                .request(new HttpCallback<HttpData<LoginInfoResponse>>(this) {

                    @Override
                    public void onSucceed(HttpData<LoginInfoResponse> result) {
                        if (result.getData() != null) {
                            EventBus.getDefault().post(new LoginStateEvent(1));
                            //昵称
                            if (!TextUtils.isEmpty(result.getData().getNickName())) {
                                personalInformationUserName.setText(result.getData().getNickName());
                            }
                            //头像
                            if (!TextUtils.isEmpty(result.getData().getAvatar())) {
                                headImageBean = result.getData().getAvatar();

                                Glide.with(PersonalInformationActivity.this)
                                        .asBitmap()
                                        .load(CommonConfiguration.splitResUrl(3, result.getData().getAvatar()))
                                        .centerCrop()
                                        .placeholder(R.drawable.icon_head_portrait)
                                        .error(R.drawable.icon_head_portrait)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                        .into(new BitmapImageViewTarget(personalInformationHeadPortraitImage) {
                                            @Override
                                            protected void setResource(Bitmap resource) {
                                                super.setResource(resource);
                                                personalInformationHeadPortraitImage.setImageBitmap(ImageUtils.toRound(resource));
                                            }
                                        });
                            }

                            //背景图
                            if (!TextUtils.isEmpty(result.getData().getBackgroundImage())) {
                                backgroundImageBean = result.getData().getBackgroundImage();
                                Glide.with(PersonalInformationActivity.this)
                                        .load(CommonConfiguration.splitResUrl(3, result.getData().getBackgroundImage()))
                                        .centerInside()
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .into(personalInformationBackgroundImage);
                            }

                            //性别
                            if (result.getData().getGender() > 0) {
                                mGender = result.getData().getGender();
                                personalInformationGender.setText(result.getData().getGender() == 1 ? "男" : "女");
                            }
                            //年龄
                            if (!TextUtils.isEmpty(result.getData().getBirth())) {
                                mBirthday = result.getData().getBirth();
                                personalInformationAge.setText(result.getData().getBirth());
                            }

                            //职业
                            if (!TextUtils.isEmpty(result.getData().getCareer())) {
                                personalInformationJob.setText(result.getData().getCareer());
                            }

                            //专业领域/爱好
                            if (result.getData().getSpeciality() != null && result.getData().getSpeciality().size() > 0) {
                                mSpecialityList = result.getData().getSpeciality();
                                StringBuilder speciality = new StringBuilder();
                                for (int i = 0; i < result.getData().getSpeciality().size(); i++) {
                                    //证明是最后一个
                                    if (i == result.getData().getSpeciality().size() - 1) {
                                        speciality.append(result.getData().getSpeciality().get(i));
                                    } else {
                                        speciality.append(result.getData().getSpeciality().get(i)).append("，");
                                    }
                                }
                                personalInformationHobby.setText(speciality);
                            }

                            //城市
                            if (!TextUtils.isEmpty(result.getData().getAreaCode())
                                    && !TextUtils.isEmpty(result.getData().getProvince())
                                    && !TextUtils.isEmpty(result.getData().getCity())
                                    && !TextUtils.isEmpty(result.getData().getArea())) {
                                mAreaCode = result.getData().getAreaCode();
                                mProvince = result.getData().getProvince();
                                mCity = result.getData().getCity();
                                mArea = result.getData().getArea();
                                personalInformationCity.setText(result.getData().getProvince() + " " + result.getData().getCity() + " " + result.getData().getArea());
                            }

                            //个人介绍
                            if (!TextUtils.isEmpty(result.getData().getDesc())) {
                                personalInformationIntroduce.setText(result.getData().getDesc());
                            }
                        }
                    }
                });
    }

    public void onProvinceCityCounty() {
        AddressPicker picker = new AddressPicker(this);
        picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY);
        picker.setTitle("选择所在地");
        picker.setDefaultValue(mProvince, mCity, mArea);
        picker.setOnAddressPickedListener(this);
        picker.show();
    }

    public void onBirthday() {
        String[] dateParts = mBirthday.split("-");
        if (dateParts.length == 3) {
            int year = Integer.parseInt(dateParts[0]);
            int month = Integer.parseInt(dateParts[1]);
            int day = Integer.parseInt(dateParts[2]);
            BirthdayPicker picker = new BirthdayPicker(this);
            picker.setDefaultValue(year, month, day);
            picker.setOnDatePickedListener(PersonalInformationActivity.this);
            picker.getWheelLayout().setResetWhenLinkage(false);
            picker.show();
        }
    }

    private void initUpdateImageApi(boolean isWatermark, boolean isMain, File imageFile) {
        EasyHttp.post(this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(imageFile)
                        .setWatermark(isWatermark))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        if (isMain) {
                            headImageBean = result.getData().getUrl();
                        } else {
                            backgroundImageBean = result.getData().getUrl();
                        }
                        saveUserInfo();
                    }
                });
    }

    //保存用户信息
    private void saveUserInfo() {
        EasyHttp.post(this)
                .api(new UserSaveApi().setNickName(personalInformationUserName.getText().toString().trim())
                        .setAvatar(headImageBean)
                        .setBackgroundImage(backgroundImageBean)
                        .setGender((personalInformationGender.getText().toString().equals("男")) ? "1" : "2")
                        .setBirth(personalInformationAge.getText().toString().trim())
                        .setCareer(personalInformationJob.getText().toString().trim())
                        .setSpeciality(mSpecialityList)
                        .setAreaCode(mAreaCode)
                        .setDesc(personalInformationIntroduce.getText().toString().trim()))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        ToastUtils.showShort("保存成功");
                    }
                });
    }

    //退出登录
    private void authLogout() {
        EasyHttp.post(this)
                .api(new AppAuthLogoutApi())
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        ToastUtils.showShort("退出登录成功");
                        EventBus.getDefault().post(new LoginStateEvent(-1));
                        kv.removeValuesForKeys(new String[]{"userTokenInfo", "userIdInfo"}); //删除多个
                        SplashActivity.start(mContext);
                        ActivityUtils.finishAllActivities();
                    }
                });
    }

    @Override
    public void onAddressPicked(ProvinceEntity province, CityEntity city, CountyEntity county) {
        mAreaCode = county.getCode();
        mProvince = province.provideText();
        mCity = city.provideText();
        mArea = county.provideText();
        personalInformationCity.setText(province.provideText() + " " + city.provideText() + " " + county.provideText());
        saveUserInfo();
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void onDatePicked(int year, int month, int day) {
        mBirthday = year + "-" + String.format("%02d", month) + "-" + String.format("%02d", day);
        personalInformationAge.setText(mBirthday);
        saveUserInfo();
    }
}
